<?php
namespace app\staff\controller;
use think\Request;
use think\Db;
use think\Controller;
use think\Config;
use think\Log;

class Index extends Controller
{

	/* 首页/列表 */
	function index(){

		$id = Request()->param('id');
		$page = Request()->param('page')?Request()->param('page'):1;
		$res = Db::table('sdzx_employee_group_relation')->alias('egr')
		->field('eg.code')
		->join('sdzx_employee_group eg','eg.id=egr.group_id')
		->where('egr.uid='.$id)
		->find();
		if($res['code']=='GJ'){				//管家首页
			$list = Db::table('sdzx_shop')->alias('s')
			->field('s.shop_owner,s.shop_name,s.shop_id,u.username,u.id')
			->join('sdzx_employee e','s.agent_id=e.id','left')
			->join('sdzx_user u','s.user_id=u.id')
			->order('s.create_time asc')
			->where("e.id=$id")
			->page($page,5)
			->select();
			$this->success('success','',$list);
		}else if($res['code']=='CG'){		//采购员首页
			$purchase = Db::table('sdzx_purchase')->alias('p')
			->join('sdzx_purchase_goods pg','p.purchase_id = pg.purchase_id')
			->field('COUNT(pg.pg_id) as num,SUM(pg.num*pg.price) as sum,p.create_time,p.purchase_id')
			->group('p.create_time')
			->where(['p.employee_id'=>$id,'p.status'=>0,'pg.status'=>0])
			->order('p.create_time asc')
			// ->page($page,5)
			->select();
			foreach ($purchase as $key => $value) {
				$list = Db::name('purchase_goods')->where(['purchase_id'=>$value['purchase_id'],'status'=>0])->select();
				$finish = 1;
				/* 判断是否采购完 1--已采购完 0--未采购完 */
				foreach ($list as $k => $val) {
					if($val['num']!=$val['real_num']){
						$finish = 0;	
					}
				}
				$purchase[$key]['finish'] = $finish;
			}
			array_multisort(array_column($purchase,'finish'), SORT_ASC,array_column($purchase,'create_time'),SORT_ASC,$purchase);
			$start = ($page-1)*5;
			$this->success('success','',array_slice($purchase,$start,5));
		}else if($res['code']=='PS'){		//配送员首页
			$res = Db::table('sdzx_shipping')
			->alias('s')
			->join('sdzx_order o','s.order_id=o.order_id')
			->join('sdzx_shop sp','o.user_id=sp.user_id','left')
			->field('s.*,o.receiver_name,o.receiver_mobile,o.receiver_address,o.receiver_pcd,DATE(o.pay_time) as time,o.order_no,o.remarks,sp.shop_name')
			->where("find_in_set($id,s.delivery_id) and order_status=40")
			->page($page,5)
			->select();
			foreach ($res as $key => $value) {
				$res[$key]['list'] = Db::name('order_goods')->where('order_id',$value['order_id'])->select();
				$res[$key]['sum'] = Db::name('order_goods')->where('order_id',$value['order_id'])->sum('num');
			}
			$this->success('success','',$res);
		}else{
			$this->error('error');
		}
		// $this->success('登陆成功','',$res);
	}
}
